#pragma once
#include "serialportdefine.h"
#include <QObject>
#include <QThread>
#include <QEventLoop>
#include <QSerialPort>
#include <QMutex>
#include <QSharedPointer>
#include <QMetaEnum>

// 串口实现类
class SerialportHandle : public QSerialPort
{
    Q_OBJECT
public:
    SerialportHandle(QObject *parent = Q_NULLPTR);
    ~SerialportHandle();

signals :
    // 接收完毕
    void sig_finished();
    // 信息槽
    void sig_recvMsg(QString name, QByteArray strRecv);

private slots:
    // 错误信号相应
    void onErrorOccurred(QSerialPort::SerialPortError error);
    // 接收信号相应
    void onReadyRead();

public :
    // 判断是否打开
    bool isOpened();
    // 设置串口信息
    void setSerialInfo(PSeriaPortInfo info);
    // 设置接收格式
    void setRecvHexData(bool bHexData = false) { m_bRecvHexData = bHexData; };

public slots:
    // 串口打开
    bool onOpenPort(QString connName);
    // 串口关闭
    void onClosePort(QString connName);
    // 数据发送
    bool onWriteData(QString connName,QString strSend,bool isHex=false, int msTimeout = 3000, bool bAsync = true);
    // 数据接收-是否超时
    bool onReadData(QString connName,QString& strRecv,int msTimeout = 3000);
    // 数据发送接收
    bool onWriteReadData(QString connName,QString strSend, QString& strRecv, bool isHex = false, int msTimeout = 3000);

private:
    // 验证是否超时
    bool wait_result_sync(int msTimeout = 3000);  //等待同步结果的返回
    QByteArray QStringHexToByteArrayHex(QString src); //将qstring转16进制
    // 转16进制
    QString ByteArrayToHexString(QByteArray data);

private:
    PSeriaPortInfo m_SerialInfo;
    QMutex* m_pRecursiveMutex = nullptr;
    QThread* m_pThread = nullptr;
    bool m_bRecvHexData = false;
    QByteArray m_temporayRecvData;
    QByteArray m_strRecv;
    QSharedPointer<QTimer> m_recevieTimer = NULL;

private slots:
    void on_receive_allData();

};

